// pages/myOrder/myOrder.js
const app = getApp();
let Api = require('../../api/api.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        ordernumber:'',
        tipText: '',
        showToast: false,
        activeTabs:'全部',
        orderList:[],
        pagestatus: '',  // pagestatus  1已付款，2待付款，5已完成，7待收货，3申请退款，4已退款，6拒绝退款   空 全部
        modifyOrderStatus: '', //modifyOrderStatus 1已付款，2待付款，5已完成，7待收货，3申请退款，4已退款，6拒绝退款, - 1 删除订单, 0 取消订单）
        totalAmount: '',
        totalAmount_1: '',
        showPayModal:false,
        orderType: '', //普通订单还是自定义订单
    },
    onLoad: function (options) {
        let self = this;
        switch (options.tabsType) {
            case '全部':
                self.setData({
                    pagestatus: '',
                    activeTabs:'全部'
                })
                break;
            case '待付款':
                self.setData({
                    pagestatus: 2,
                    activeTabs: '待付款'
                })
                break;
            case '待发货':
                self.setData({
                    pagestatus: 1,
                    activeTabs: '待发货'
                })
                break;
            case '待收货':
                self.setData({
                    pagestatus: 7,
                    activeTabs: '待收货'
                })
                break;
            case '退款':
                self.setData({
                    pagestatus: '3,4,6',
                    activeTabs: '退款'
                })
                break;
        }
        //加载列表数据
        self.loadListData();
    },
    /**
     * 加载列表数据
     */
    loadListData: function () {
        let self = this;
        Api.get(app.globalData.mallDomain, { //18）我的订单列表 
            doShowMyOrderList: 1,
            token: app.globalData.token,
            status: self.data.pagestatus,
            pagesize:99999,
            pageindex:1,
        }).then(res => {
            let list = [];
            console.log(res, '我的订单列表')
            if (res.data.list != '') {
                res.data.list.forEach(ele => {
                    let listdata = self.newList(ele.list);
                    let woIntAll = 0;
                    //计算总件数
                    if (listdata != undefined && listdata != null && listdata != ''){
                        listdata.forEach(ret => {
                            woIntAll += parseInt(ret.woInt)
                        })
                    }
                    //插入数据
                    list.push({
                        orderstatus: (ele.orderstatus == 1 ? '已付款' : ele.orderstatus == 2 ? '待付款' : ele.orderstatus == 5 ? '已完成' : ele.orderstatus == 7 ? '待收货' : ele.orderstatus == 3 ? '申请退款' : ele.orderstatus == 4 ? '已退款' : ele.orderstatus == 6 ? '拒绝退款' : ele.orderstatus == 0 ? '已取消' : ''),
                        list: listdata,
                        woIntAll: woIntAll,
                        subtotal: parseInt(ele.ordermoney),
                        subtotal_1: ele.ordermoney.substring(ele.ordermoney.length - 2, ele.ordermoney.length),
                        ordermoney: ele.ordermoney,
                        ordertotalfee: ele.ordertotalfee,
                        name: ele.name,
                        phone: ele.phone,
                        address: ele.address,
                        ordernumber: ele.ordernumber,
                        orderid: ele.orderid,
                        orderrefundfee: ele.orderrefundfee,
                        courier: ele.courier,
                        courierorder: ele.courierorder,
                        orderremark: ele.orderremark,
                        ordercreatetime: ele.ordercreatetime,
                        orderpaytime: ele.orderpaytime,
                        orderdeliverytime: ele.orderdeliverytime,
                        orderrefundfee: ele.orderrefundfee,
                        orderbacktime: ele.orderbacktime,
                        orderoverpd: ele.orderoverpd,
                        orderRefundContent: ele.OrderRefundContent, //退款原因
                        orderRefundDesc: ele.OrderRefundDesc,  //退款说明
                        orderRefundImg: ele.OrderRefundImg, //退款图
                        orderRefundCreateTime: ele.OrderRefundCreateTime,  //退款创建时间
                        orderRefundType: ele.OrderRefundType, //1、退货退款。2、仅退货
                    })
                })
            }
            
            self.setData({
                orderList: list
            })
        })
    },
    /**
     * 点击取消按钮，关闭弹出框
     */
    closeBg: function (e) {
        let self = this;
        self.setData({
            showPayModal: false,
        })
    },
    /*
    **点击我的订单列表里的按钮
    */
    clickMyOrderBtn: function (e) {
        let self = this;
        console.log(e)
        switch (e.currentTarget.dataset.text) {
            case '已付款':  //点击修改地址 --修改地址
                wx.navigateTo({
                    url: '../addAddress/addAddress?type=myOrder&ordernumber=' + e.currentTarget.dataset.ordernumber
                })
                break;
            case '确认收货': //点击确认收货
                self.setData({
                    modifyOrderStatus: "5"
                })
                wx.showModal({
                    title: '',
                    content: '确认要收货吗？',
                    cancelColor: '#1672fb',
                    confirmColor: '#1672fb',
                    success: function (res) {
                        if (res.confirm == true) {
                            self.modifyOrder(e.currentTarget.dataset.ordernumber, e.currentTarget.dataset.text);
                        }
                    },
                })
                break;
            case '再次申请': //点击再次申请
                self.setData({
                    modifyOrderStatus: "3"
                })
                Api.get(app.globalData.mallDomain, { //19）修改订单状态
                    doChangeOrderStatus: 1,
                    token: app.globalData.token,
                    status: 3,
                    ordernumber: e.currentTarget.dataset.ordernumber, // 订单号
                    type: e.currentTarget.dataset.orderrefundtype,
                    content: e.currentTarget.dataset.orderrefundcontent,
                    desc: e.currentTarget.dataset.orderrefundcontent,
                    img: e.currentTarget.dataset.orderrefundimg,
                }).then(res => {
                    console.log(res)
                    if (res.data.msg == '118') {
                        self.setData({
                            tipText: '提交成功',
                            showToast: true,
                        })
                        setTimeout(function () {
                            let up = "orderList[" + e.currentTarget.dataset.index + "].orderstatus"
                            self.setData({
                                tipText: '',
                                showToast: false,
                                [up]:'申请退款'
                            })
                         
                        }, 1000)
                    }
                })
                break;
            case '删除订单': //点击订单状态等于 已退款 和  已完成
                self.setData({
                    modifyOrderStatus: "-1"
                })
                wx.showModal({
                    title: '',
                    content: '确认要删除订单吗？',
                    cancelColor: '#1672fb',
                    confirmColor: '#1672fb',
                    success: function (res) {
                        if (res.confirm == true) {
                            self.modifyOrder(e.currentTarget.dataset.ordernumber, e.currentTarget.dataset.text);
                        }
                    },
                })
                break;
            case '取消订单': //点击取消订单
                self.setData({
                    modifyOrderStatus: "0"
                })
                wx.showModal({
                    title: '',
                    content: '确认要取消订单吗？',
                    cancelColor: '#1672fb',
                    confirmColor: '#1672fb',
                    success: function (res) {
                        if (res.confirm == true) {
                            self.modifyOrder(e.currentTarget.dataset.ordernumber, e.currentTarget.dataset.text);
                        }
                    },
                })
                break;
            case '去支付': //点击去支付
                self.setData({
                    ordernumber: e.currentTarget.dataset.ordernumber,
                    totalAmount: e.currentTarget.dataset.subtotal,
                    totalAmount_1: e.currentTarget.dataset.subtotal_1,
                    modifyOrderStatus: "5",
                    showPayModal: true,
                    orderType:'普通订单'  //初始化先把orderType设置为普通订单 循环有自定义订单在修改orderType值
                })
                for(let i= 0 ; i < self.data.orderList.length; i ++){
                    if (self.data.orderList[i].customvalue != ''){
                        self.setData({
                            showPayModal: true,
                            orderType: '自定义订单'
                        })
                    }
                }
                break;
        }
    },
    /**
     * 修改订单
     */
    modifyOrder(num, types) {
        let self = this;
        Api.get(app.globalData.mallDomain, { //19）修改订单状态 
            doChangeOrderStatus: 1,
            token: app.globalData.token,
            status: self.data.modifyOrderStatus,
            ordernumber: num,
        }).then(res => {
            if (types == '取消订单') { //点击取消订单按钮 成功 修改订单状态
                if (res.data.msg == '118') {
                    self.setData({
                        tipText: '订单已取消！',
                        showToast: true,
                    })
                    for (let i = 0; i < self.data.orderList.length; i++) {
                        if (num == self.data.orderList[i].ordernumber) {
                            if (self.data.activeTabs == '全部') {
                                let up = "orderList[" + i + "].orderstatus";
                                self.setData({
                                    [up]: '已取消',
                                })
                            } else if (self.data.activeTabs == '待付款') { //移除待付款列表中的已取消订单
                                let listData = self.data.orderList;
                                listData.splice(i, 1); // 如果数据组存在该元素，则把该元素删除
                                self.setData({
                                    orderList: listData
                                })
                            }

                        }
                    }
                }
            } else if (types == '删除订单') { // 点击删除订单按钮 成功 移除列表数据
                if (res.data.msg == '118') {
                    self.setData({
                        tipText: '订单已删除！',
                        showToast: true,
                    })
                    for (let i = 0; i < self.data.orderList.length; i++) {
                        if (num == self.data.orderList[i].ordernumber) {
                            let listData = self.data.orderList;
                            listData.splice(i, 1); // 如果数据组存在该元素，则把该元素删除
                            self.setData({
                                orderList: listData
                            })
                        }
                    }
                }
            } else if (types == '确认收货') { //点击确认收货按钮
                console.log(res,'确认收货返回结果')
                if (res.data.msg == '118') {
                    self.setData({
                        tipText: '收货完成！',
                        showToast: true,
                    })
                    for (let i = 0; i < self.data.orderList.length; i++) {
                        if (num == self.data.orderList[i].ordernumber) {
                            if (self.data.activeTabs == '全部') {
                                let up = "orderList[" + i + "].orderstatus";
                                self.setData({
                                    [up]: '已完成',
                                })
                            } else if (self.data.activeTabs == '待收货') { //移除待收货列表中的已完成列表
                                let listData = self.data.orderList;
                                listData.splice(i, 1); // 如果数据组存在该元素，则把该元素删除
                                self.setData({
                                    orderList: listData
                                })
                            }
                        }
                    }
                }
            }
            setTimeout(function () {
                self.setData({
                    tipText: '',
                    showToast: false
                })
            }, 1000)
            console.log(res)
        })
    },
    /**
     * 立即支付
     */
    immediatelyPay: function (e) {
        let self = this;
        self.setData({
            showPayModal: false,
        })
        //  25、支付请求接口
        Api.get(app.globalData.payUrl, {
            token: app.globalData.token,
            ordernumber: self.data.ordernumber,
        }).then(res => {
            console.log(res)
            wx.requestPayment({
                timeStamp: res.data.timeStamp,
                nonceStr: res.data.nonceStr,
                package: res.data.package,
                signType: res.data.signType,
                paySign: res.data.paySign,
                success: function (res) {
                    wx.showToast({
                        title: '支付成功',
                        icon: 'success',
                        duration: 1000
                    })
                    setTimeout(function () {
                        for (let i = 0; i < self.data.orderList.length ; i++ ){
                            if (self.data.ordernumber == self.data.orderList[i].ordernumber){
                                if (self.data.orderList[i].name.replace(/\s+/g, "") == '' && self.data.orderList[i].phone.replace(/\s+/g, "") == '' && self.data.orderList[i].address.replace(/\s+/g, "") == '') {  //如果姓名 手机号 地址都为空 那么该订单发送类型为送他人
                                    wx.redirectTo({
                                        url: '../paySuccess/paySuccess?sendType=送他人&orderType=' + self.data.orderType + '&ordernumber=' + self.data.ordernumber
                                    })
                                } else {
                                    wx.redirectTo({
                                        url: '../paySuccess/paySuccess?sendType=送自己&orderType=' + self.data.orderType + '&ordernumber=' + self.data.ordernumber
                                    })
                                }
                            }
                        }
                        
                      
                    }, 2000)
                },
            })
        })
    },
    /*
    **进入订单详情页面
    */
    showOrderDetail:function(e){
        if (e.currentTarget.dataset.name.replace(/\s+/g, "") == '' && e.currentTarget.dataset.phone.replace(/\s+/g, "") == '' && e.currentTarget.dataset.address.replace(/\s+/g, "") == ''){  //如果姓名 手机号 地址都没空 那么改订单发送类型为送他人
            wx.navigateTo({
                url: '../orderDetail/orderDetail?orderstatus=' + e.currentTarget.dataset.orderstatus + '&sendType=送他人&ordernumber=' + e.currentTarget.dataset.ordernumber
            })
        }else{
            wx.navigateTo({
                url: '../orderDetail/orderDetail?orderstatus=' + e.currentTarget.dataset.orderstatus + '&sendType=送自己&ordernumber=' + e.currentTarget.dataset.ordernumber
            })
        }
        
    },
    /**
     * 重组列表list数据
     */
    newList(val){
        let self = this;
        let dataList = [];
        val.forEach(ele => {
            let arr = ele.customvalue.split(",");
            let arr_1 = '';
            if (arr != undefined && arr != null && arr != '' ){
                arr_1 = arr
            }else{
                arr_1 = ele.wsOneValue
            }
            dataList.push({
                wpName: unescape(ele.wpName),
                wpCover: ele.wpCover,
                wsPrice: parseInt(ele.wsPrice),
                wsPrice_1: ele.wsPrice.substring(ele.wsPrice.length - 2, ele.wsPrice.length),
                WoAmount: ele.WoAmount,
                woInt: ele.woInt,
                wsOneValue: ele.wsOneValue,
                wpViceName: ele.wpViceName,
                wpId: ele.wpId,
                customvalue: arr_1,
            })
        })
        return dataList;
    },
    /**
     * 点击tabs
     */
    clickTabs: function (e) {
        let self = this;
        if (e.currentTarget.dataset.text == '全部') {
            self.setData({
                activeTabs: '全部',
                pagestatus: ''
            })
        } else if (e.currentTarget.dataset.text == '待付款') {
            self.setData({
                activeTabs: '待付款',
                pagestatus: 2
            })
        } else if (e.currentTarget.dataset.text == '待发货') {
            self.setData({
                activeTabs: '待发货',
                pagestatus: 1
            })
        } else if (e.currentTarget.dataset.text == '待收货') {
            self.setData({
                activeTabs: '待收货',
                pagestatus: 7
            })
        } else if (e.currentTarget.dataset.text == '退款') {
            self.setData({
                activeTabs: '退款',
                pagestatus: '3,4,6'
            })
        }
        //加载列表数据
        self.loadListData();

    },


})